package thread.lock;

import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author hanchao
 * @date 2017/5/15 15:18
 */
public class ReadWriteLockDemo {
    private static final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
    public static void main(String[] args){
        for (int i = 0; i < 10; i++) {
            new Thread("线程"+i){
                @Override
                public void run() {
                    if(Thread.currentThread().getName().contains("2")){
                        lock.writeLock().lock();
                        System.out.println(Thread.currentThread().getName()+"获取到了写锁");
                        try {
                            Thread.sleep(1000);
                        } catch(Exception e){
                            e.printStackTrace();
                        }
                        lock.writeLock().unlock();
                    }
                    lock.readLock().lock();
                    System.out.println(Thread.currentThread().getName()+"获取到了读锁");
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.readLock().unlock();

                }
            }.start();
        }
    }
}
